package org.ruoyi.graph2.service.impl;

import cn.hutool.core.map.MapBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ruoyi.common.core.domain.R;
import org.ruoyi.graph2.domain.bo.GraphBaseBo;
import org.ruoyi.graph2.domain.vo.GraphBaseVo;
import org.ruoyi.graph2.mapper.GraphBaseMapper;
import org.ruoyi.graph2.service.IGraphBaseService;
import org.ruoyi.graph2.domain.bo.KnowledgeNodeBo;
import org.ruoyi.graph2.utils.WordDocumentParser;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.*;

/**
 * 图谱基础信息表Service业务层处理
 *
 * @author ageerle
 * @date Tue Nov 18 15:28:04 CST 2025
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GraphBase2ServiceImpl {

    private final GraphBaseMapper baseMapper;

	private final IGraphBaseService graphBaseService;

	private final WordService wordService;

	private final Neo4jService neo4jService;


	public R<Map<String, Object>> queryGraphByKnowledge(long graphBaseId, Integer limit) {
		GraphBaseVo graphBase = graphBaseService.queryById(graphBaseId);

		if (graphBase == null) {
			return R.fail("图谱不存在");
		}

		String graphGroup = graphBase.getGraphGroup();
		try {
			// 查询节点
			List<Map> nodes = neo4jService.queryVerticesByGraphGroup(graphGroup, limit);

			// 查询关系
			List<Map> edges = neo4jService.queryEdgesByGraphGroup(graphGroup, limit);

			Map<String, Object> result = new HashMap<>();
			result.put("nodes", nodes);
			result.put("edges", edges);
			result.put("graphGroup", graphGroup);
			result.put("graphTitle", graphBase.getGraphTitle());

			return R.ok(result);
		} catch (Exception e) {
			return R.fail("获取图谱数据失败: " + e.getMessage());
		}
	}

	public R uploadWord(String title, MultipartFile file) throws Exception {
		// 创建临时文件
		File tmp = File.createTempFile("graph", file.getOriginalFilename());
		file.transferTo(tmp);

		String graphGroup = UUID.randomUUID().toString();

		// 解析Word文档
		parseWordToGraph(tmp.getAbsolutePath(), graphGroup);

		// 保存图谱基础信息
		GraphBaseBo graphBaseBo = new GraphBaseBo();
		graphBaseBo.setGraphGroup(graphGroup);
		graphBaseBo.setGraphTitle(title);
//		graphBaseBo.setTotalNodes(0);
//		graphBaseBo.setTotalRelationships(0);
//		graphBaseBo.setNodeTypeDistribution("");
//		graphBaseBo.setRelationTypeDistribution("");
//		graphBaseBo.setCreateBy(1L);
//		graphBaseBo.setUpdateBy(1L);
		graphBaseBo.setCreateTime(new Date());
		graphBaseBo.setUpdateTime(new Date());
		graphBaseService.insertByBo(graphBaseBo);

		tmp.delete();

		return queryGraphByKnowledge(graphBaseBo.getId(), 100);
	}

	public R saveGraph(long graphBaseId, String graphJson) {
		List<Map> nodes = new ArrayList<>();
		List<Map> edges = new ArrayList<>();
		String graphGroup = StringUtils.EMPTY;
		String graphTitle = StringUtils.EMPTY;
		try {
			Map<String, Object> graphMap = new ObjectMapper().readValue(graphJson, Map.class);

			// 节点
			nodes = (List<Map>) graphMap.get("nodes");

			// 关系
			edges = (List<Map>) graphMap.get("edges");

			graphGroup = (String) graphMap.get("graphGroup");

			graphTitle = (String) graphMap.get("graphTitle");
		} catch (Exception e) {
			log.error("解析图谱数据失败: " + e.getMessage());

			return R.fail("服务器繁忙，请稍后重试", MapBuilder.create().put("message", e.getMessage()).build());
		}

		neo4jService.saveKnowledgeGraph(nodes, edges, graphGroup);

		// 更新图谱基础信息
		GraphBaseBo graphBaseBo = new GraphBaseBo();
		graphBaseBo.setId(graphBaseId);
		graphBaseBo.setUpdateTime(new Date());
		graphBaseService.updateByBo(graphBaseBo);

		return queryGraphByKnowledge(graphBaseId, 100);
	}

	public R deleteGraph(long graphBaseId) {
		GraphBaseVo graphBase = graphBaseService.queryById(graphBaseId);
		String graphGroup = graphBase.getGraphGroup();
		boolean deleted = neo4jService.deleteGraph(graphGroup);
		if (deleted) {
			baseMapper.deleteById(graphBaseId);
		}
		return deleted? R.ok() : R.fail("删除图谱失败");
	}


	private String parseWordToGraph(String wordFilePath, String graphGroup) {
		try {
			// 1. 解析Word文档
			List<KnowledgeNodeBo> nodes = WordDocumentParser.parseDocument(wordFilePath, graphGroup);

			log.info("解析到 " + nodes.size() + " 个知识节点");

			// 2. 存储到Neo4j
			neo4jService.createKnowledgeGraph(nodes);

			log.info("知识图谱已成功保存到Neo4j");

			// 3. 打印节点信息（可选）
			for (KnowledgeNodeBo node : nodes) {
				log.info("节点: " + node.getFullPath() + " " + node.getTitle() +
					" (" + node.getLevel() + ")");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}


//		try (FileInputStream fis = new FileInputStream(wordFilePath);
//			 XWPFDocument document = new XWPFDocument(fis)) {
//
//			String currentTitle = null;
//			StringBuilder currentContent = new StringBuilder();
//			Map<String, String> numberingMap = new HashMap<>();
//
//			StringBuilder sb = new StringBuilder();
//
//			for (XWPFParagraph paragraph : document.getParagraphs()) {
//				String text = paragraph.getText().trim();
//				if (text.isEmpty()) continue;
//				sb.append("\n");
//				sb.append(text);
//			}
//
//			GraphExtractionResult result = wordService.extractFromTextWithModel(sb.toString(), "deepseek-v3.1");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}




		return graphGroup;
	}
}
